# encoding:utf-8
import sys 
import time
from werkzeug.security import generate_password_hash
import xconfig as xconfig
from apps import config
from apps.init_app import app, mongo
from flask_script import Manager
__author__ = "adog"

manager = Manager(app)


@manager.command
def init_site():

    '''
    初始化root用户角色, 管理员, 管理员基本资料
    :return:
    '''
    # 创建超级用户角色,存在则不创建
    print('第一个管理员用户初始化')
    username = input("输入用户名:")
    email = input("输入email:")

    password = input("输入密码,至少8个字符:")
    
    print('创建数据库库collection')
    try:
        print('创建role collection...')
        mongo.db.create_collection("role")
    except Exception as e:
        print (e)
    try:
        print('创建user collection...')
        mongo.db.create_collection("user")
    except Exception as e:
        print (e)
    
    print("创建role角色...")
    _id = mongo.db.role.insert({
        "name":"Root",
        "default":False,
        "permissions":config.Role().ROOT,  # config["permission"].ROOT,
        "instructions":'ROOT',

    })
    
    role_root = mongo.db.role.find_one({"permissions":config.Role.ROOT})
    role_id = role_root['_id']
    password_hash = generate_password_hash(password)
    print('创建ROOT用户...')
    user = {"username":username.strip(),
            "email":email.strip(),
            "password":password_hash,
            "create_at":time.time(),
            "role_id":role_id
            }
    mongo.db.user.insert(user)
    
    print('刚创建的用户登录信息如下:')
    print("用户名:{}\nEmail:{}\n".format(username, email))


if __name__ == "__main__":
    if 0:
        # no need : if using console, need sys.arg 'init_site'  (note: not '--init_site', but only 'init_site')
        sys.argv.append('init_site')
        manager.run()
        '''
        第一个管理员用户初始化
        输入用户名:adog
        输入email:x@x.com
        输入密码,至少8个字符:adogwert
        '''
    elif 1:
        port = xconfig.webserver_port
        if len(sys.argv) >= 2:
            if '--port=' in sys.argv[1]:
                port = int(sys.argv[1].split('=')[-1])
        app.run(host='0.0.0.0', port=9095, threaded=True)  
    
